<template>
    <!-- 短链生成对话框 -->
    <el-dialog
    	:visible.sync="visible"
    	title="投放渠道"
    	custom-class="short-link-dialog"
    	:before-close="handleDialogClose"
        :close-on-click-modal="false"
        append-to-body
    	width="360px">
    	<el-form 
    		:model="formData" 
    		:rules="rules" 
    		ref="formRef">
    		<el-form-item prop="from" class="item-from">
    		    <el-radio-group v-model="formData.from" @change="handleRadioChange">
                    <el-radio 
                        v-for="(item, index) of fromList" 
                        :key="index" 
                        :label="item.value">
                        {{item.label}}
                    </el-radio>
                </el-radio-group>
    		</el-form-item>
    		<el-form-item prop="type" class="item-type">
    		    <el-radio-group v-model="formData.type" @change="handleRadioChange">
                    <el-radio 
                        v-for="(item, index) of typeList" 
                        :key="index" 
                        :label="item.value">
                        <template v-if="item.value != 'custom'">{{item.label}}</template>
    		            <el-form-item
                            v-else
                            prop="code" 
                            :rules="rules.code">
			                <el-input 
			                	size="small" 
			                	placeholder="自定义(如：sms、aicall)" 
			                	v-model="formData.code"
                                :disabled="formData.type != 'custom'"
                                maxlength="20">
			                </el-input>
    		            </el-form-item>
                    </el-radio>
                </el-radio-group>
    		</el-form-item>
    	</el-form>
    	<template slot="footer" class="dialog-footer">
    		<el-button @click="handleDialogClose" size="small">取 消</el-button>
    		<el-button type="primary" @click="handleShortLinkCreate" size="small">确 定</el-button>
            <span ref="copyUrl" class="copy-short-link" @click="copyUrl" :data-clipboard-text="shortUrl"></span>
    	</template>
    </el-dialog>
</template>
<script>
    import Clipboard from "clipboard"
    import { dateFormatter } from "@/common/js/util.js"
    export default({
        props: {
            type: String,
            options: {
                type: Object,
                default: () => ({
                    visible: false,
                    row: {}
                })
            }
        },
        data() {
            return {
                visible: false,
                formData: {             // 短链生成form表单
                    from: '',           // 来源哪个小程序
                    type: '',
                    code: ''
                },
                typeList: [
                    {label: '短信群发链接（SMS）', value: 'sms'},
                    {label: '语音外呼（Alcall）', value: 'aicall'},
                    {label: '自定义', value: 'custom'}
                ],
                fromList: [
                    {label: '车家佳小程序', value: 'chejj'},
                    {label: '元通汽车小程序', value: 'ytShop'}
                ],
                rules: {
					from: [{ required: true, message: '请选择小程序', trigger: ['blur', 'change'] }],
					type: [{ required: true, message: '请选择渠道类型', trigger: 'change' }],
					code: [{ required: false, message: '请输入自定义内容', trigger: ['blur', 'change'] }]
                },
                shortUrl: '3333'
            }
        },
        watch: {
            options: function(val) {
                const { visible, row } = val
                if (visible) {
                    this.visible = visible
                }
            }
        },
        methods: {
            handleDialogClose() {
                this.$refs.formRef.resetFields()
                this.visible = false
            },
            handleRadioChange(val) {
                if (val  === 'custom') {
                    this.rules.code[0].required = true
                } else {
                    this.rules.code[0].required = false
                }
            },
            getLinkUrl() {
                let domain = document.domain
				if (domain != 'admin.mycjj.com' && domain != 'admin.chejj.cn') {
					domain = 'admin.chejj.cn'
				}
				return location.protocol + '//' +domain.replace('admin', 'web') + '/member/programLinks/programLinks.html?message='
            },
            handleShortLinkCreate(e) {
				this.$refs.formRef.validate(async valid => {
                    if (valid) {
                        let group_id, group_name, store_id, channel, miniurl
                        const apiUrl = '/admin/newCarGroupBuy/index.php?act=groupBuy&op=getShortUrl'
                        let { from, type, code } = this.formData
                        if (type === 'custom') type = code
                        if (this.type === 'newcar') {
                            group_id = this.options.row.ncgb_id
                            group_name = this.options.row.ncgb_title_name
                            store_id = this.options.row.ncgb_store_id
                            channel = `${group_id}_ncg_${type}_${dateFormatter("YYMMDD")}`
                            miniurl = '/pages/newCarGroup/newCarGroupdetail/newCarGroupdetail'
                        } else {
                            group_id = this.options.row.asgb_id
                            group_name = this.options.row.asgb_title_name
                            store_id = this.options.row.asgb_store_id
                            channel = `${group_id}_asg_${type}_${dateFormatter("YYMMDD")}`
                            miniurl = '/pages/aftersale/aftersaledetail/aftersaledetail'
                        }
                        const message = {
                            miniurl, store_id, group_id, source: this.type, from, channel
                        }
                        const datas = { 
                            group_id,
                            store_id,
                            url: this.getLinkUrl() + JSON.stringify(message), 
                            name: group_name,
                            channel
                        }
                        const res = await this.$http.get(apiUrl, { params: datas })
                        
                        if (res.code == 1) {
                                this.shortUrl = res.data.short_url
                                this.$nextTick(() => this.$refs['copyUrl'].click())
                                this.handleDialogClose()
                            } else {
                                this.$message.error(res.msg)
                            }
                    }
                })
            },
            copyUrl(e) {
                // 复制链接
                const clipboard = new Clipboard('.copy-short-link')
                clipboard.on('success', e => {
                    this.$message.success('已成功复制到剪切板')
                    clipboard.destroy() // 释放
                })
                clipboard.on('error', e => {
                    this.$message.error('复制失败')
                    clipboard.destroy() // 释放
                })
            }
        }
    })
</script>
<style lang="scss">
    .short-link-dialog {
        .item-type {
            margin-bottom: 0;
            .el-radio-group {
                width: 100%;
            }
            .el-radio {
                width: 100%;
                display: block;
                margin-bottom: 14px;
                display: flex;
                align-items: center;
            }
            .el-radio:last-child {
                &, .el-form-item {
                    margin-bottom: 4px;
                }
            }
        }
        .item-from .el-radio-group {
            display: flex;
        }
        .el-dialog__body {
            padding-bottom: 10px;
        }
        .el-form-item__content {
            line-height: 32px;
        }
        .el-input {
            width: 290px;
        }
    }
</style>